package com.nf.health.app.utils;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
/*import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.hp.hpl.sparta.xpath.ThisNodeTest;*/

/**
 * 百度定位  补充
 * @author 于亚豪
 */
public class LocationUtil {
	public static LocationClient mLocationClient = null;
	public static double latitude = -1;// 纬度
	public static double longitude = -1;// 经度
	public static String completeAddr;
	private static final int UPDATE_TIME = 5 * 60 * 1000;
	private static CallBack callBack;
	private static CallAddressBack callAddressBack;
	private static CallRemainQequestFaild callRemainQequestFaild;
	private static Context context;
	public interface CallRemainQequestFaild{
		void callRemainQuestFaild();
	}
	
	public interface CallBack {
		/***** 如果latitude和longitude的值为-1则为定位失败 ******/
		void complete(double latitude, double longitude);
	}
	public interface CallAddressBack {
		/***** 如果latitude和longitude的值为-1则为定位失败 ******/
		void complete(double latitude, double longitude, String address);
		/***** 如果latitude和longitude 定位失败 ******/
		void callRemainQuestFaild();
	}
	public interface CallAddress extends CallAddressBack{
		void addressInfo(String province,String city,String district);
	}
	public void registCallRemainQequestFaild(CallRemainQequestFaild CallRemainQequestFaild){
		this.callRemainQequestFaild = CallRemainQequestFaild;
	}
	public static void initial(Context mContext, CallBack back) {
		context = mContext;
		callBack = back;
		mLocationClient = new LocationClient(mContext);
		mLocationClient.registerLocationListener(new MyLocationListener());
		InitLocation();
		mLocationClient.start();
	}
	/*************返回带有定位地址的地址*********/
	public static void initial(Context mContext, CallAddressBack back) {
		context = mContext;
		callAddressBack = back;
		mLocationClient = new LocationClient(mContext);
		mLocationClient.registerLocationListener(new MyLocationListener());
		InitLocation();
		mLocationClient.start();
	}

//	public static void initGeoCode(Context cnt, String city, String address,
//			CallBack back) {
//		context = cnt;
//		callBack = back;
//		GeoCoder mSearch = GeoCoder.newInstance();
//		mSearch.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
//
//			@Override
//			public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
//				// TODO Auto-generated method stub
//
//			}
//
//			@Override
//			public void onGetGeoCodeResult(GeoCodeResult result) {
//				// TODO Auto-generated method stub
//				if (result == null) {
//					callBack.complete(0, 0);
//					callAddressBack.complete(0, 0,"");
//				} else {
//					// String strInfo =
//					// String.format("纬度：%f 经度：%f",result.getLocation().latitude,
//					// result.getLocation().longitude);
//					// Log.i("@@@", "strInfo   " + strInfo);
//					if ((result.getLocation() != null)) {
//						callBack.complete(result.getLocation().latitude,
//								result.getLocation().longitude);
//						if(!TextUtils.isEmpty(result.getAddress())){
//							callAddressBack.complete(result.getLocation().latitude,
//									result.getLocation().longitude,result.getAddress());
//						}
//					} else {
//						callBack.complete(0, 0);
//						callAddressBack.complete(0, 0,"");
//					}
//				}
//			}
//		});
//
//		mSearch.geocode(new GeoCodeOption().city(city).address(address));
//	}

	/**
	 * 初始化定位数据
	 */
	private static void InitLocation() {
		// String tempcoor="gcj02";
		String tempcoor = "bd09ll";
		// String tempcoor="bd09";

		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);// 设置定位模式
		option.setCoorType(tempcoor);// 返回的定位结果是百度经纬度，默认值gcj02
		option.setScanSpan(UPDATE_TIME);// 设置发起定位请求的间隔时间
		option.setIsNeedAddress(true);// 显示中文地址信息
		mLocationClient.setLocOption(option);
	}

	/**
	 * 实现实位回调监听
	 */
	public static class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			String province = location.getProvince();//省
			String city = location.getCity();		 //市
			String district = location.getDistrict();//区
			PreferenceHelper.saveLocation(province,city,district);
			// Receive Location
			StringBuffer sb = new StringBuffer(256);
			sb.append("time : ");
			sb.append(location.getTime());
			sb.append("\nerror code : ");
			sb.append(location.getLocType());
			sb.append("\nlatitude : ");
			sb.append(latitude);
			sb.append("\nlontitude : ");
			sb.append(longitude);
			sb.append("\nradius : ");
			sb.append(location.getRadius());
			if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位成功
				sb.append("\nspeed : ");
				sb.append(location.getSpeed());
				sb.append("\nsatellite : ");
				sb.append(location.getSatelliteNumber());
				sb.append("\ndirection : ");
				sb.append("\naddr : ");
				completeAddr = location.getAddrStr() + location.getDirection();
				sb.append(completeAddr);

				// 为经纬度赋值
				latitude = location.getLatitude();
				longitude = location.getLongitude();
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位成功
				sb.append("\naddr : ");
				completeAddr = location.getAddrStr();
				sb.append(completeAddr);
				// 运营商信息
				sb.append("\noperationers : ");
				sb.append(location.getOperators());

				// 为经纬度赋值
				latitude = location.getLatitude();
				longitude = location.getLongitude();
			}
			completeAddr = location.getAddrStr() + location.getDirection();
			Log.i("@@@", completeAddr);
			mLocationClient.stop();
			//红米手机 禁用读取位置权限，城市全为空 ，但是 经纬度不为空
			if(TextUtils.isEmpty(province) && TextUtils.isEmpty(city) && TextUtils.isEmpty(district)){
				callAddressBack.callRemainQuestFaild();
				return;
			}
			//判断当前定位是否成功
			if (latitude == -1 || longitude == -1) {
				//失败给予提示
				//GetToast.useString(context, "定位失败");
				if(callAddressBack != null){
					callAddressBack.callRemainQuestFaild();
				}
			} else {
				//成功执行回调 
				if(callBack != null){
					callBack.complete(latitude, longitude);
				}
				if(callAddressBack != null){
					callAddressBack.complete(latitude, longitude,completeAddr);
					if(callAddressBack instanceof CallAddress) {
						CallAddress callAddress = (CallAddress) callAddressBack;
						callAddress.addressInfo(province, city, district);
					}
				}
					
			}

		}

	}

	/**
	 * 返回距离千米
	 * 
	 * @param lat1
	 * @param lon1
	 * @param lat2
	 * @param lon2
	 * @return
	 */
	public static double getDistance(double lat1, double lon1, double lat2,
			double lon2) {
		float[] results = new float[1];
		Location.distanceBetween(lat1, lon1, lat2, lon2, results);
		return StringUtil.rounded(results[0] / 1000, 2);
	}

	// 返回当前位置详细地址
	public static String getCompleteAddr() {
		return completeAddr;
	}


	/**
	 * 判断GPS是否被打开
	 * @param cnt
	 * @return
	 */
	public static boolean isOpenGPS(Context cnt){
		LocationManager locationManager = (LocationManager)cnt.getSystemService(Context.LOCATION_SERVICE);
		return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
	}

	/**
	 * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的  建议以后定位就用这个方法
	 * @param context
	 * @return true 表示开启
	 */
	public static final boolean gpsIsOpen(final Context context) {
		LocationManager locationManager
				= (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		// 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
		boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
		// 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
		boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		if (gps || network) {
			return true;
		}
		return false;
	}
	/**
	 * GPS设置页面
	 * @param cnt
	 * @return
	 */
	public static void setGoGPSMain(Context cnt){
		//进入GPS设置页面
		Intent intent = new Intent();
		intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		try
		{
			cnt.startActivity(intent);


		} catch(ActivityNotFoundException ex)
		{

			// The Android SDK doc says that the location settings activity
			// may not be found. In that case show the general settings.

			// General settings activity
			intent.setAction(Settings.ACTION_SETTINGS);
			try {
				cnt.startActivity(intent);
			} catch (Exception e) {
			}
		}
	}

}
